package io.renren.util;

import com.google.gson.Gson;
import com.netflix.hystrix.HystrixCommand;
import com.netflix.hystrix.HystrixCommandGroupKey;
import com.netflix.hystrix.HystrixCommandProperties;
import com.squareup.okhttp.*;
import io.renren.vo.RespModel;
import org.apache.commons.lang.StringUtils;

import java.util.HashMap;
import java.util.concurrent.TimeUnit;

/**
 * Created by schen on 12/16/15.
 */
public class SmsSendUtil extends HystrixCommand<String> {
	public static final MediaType MEDIA_TYPE_JSON = MediaType.parse("application/json");
	private String applicationId;
	private String phone;
	private String msg;
	private String type;
	private String url;
	private final OkHttpClient client = new OkHttpClient();
	private final Gson gson = new Gson();

	public SmsSendUtil(String url, String applicationId, String phone,
                       String msg, String type) {
		super(Setter.withGroupKey(
				HystrixCommandGroupKey.Factory.asKey("MsgService"))
				.andCommandPropertiesDefaults(HystrixCommandProperties.Setter().withExecutionTimeoutInMilliseconds(30 * 1000)));

		client.setConnectTimeout(30, TimeUnit.SECONDS);
		client.setReadTimeout(30, TimeUnit.SECONDS);
		client.setWriteTimeout(30, TimeUnit.SECONDS);
		this.applicationId = applicationId;
		this.phone = phone;
		this.msg = msg;
		this.type = type;
		this.url = url;
	}

	@Override
	protected String run() throws Exception {
		HashMap<String, String> payload = new HashMap<String, String>();
		payload.put("applicationId", applicationId);
		payload.put("type", type);
		payload.put("phone", phone);
		payload.put("message", msg);

		Request request = new Request.Builder()
				.url(url)
				.post(RequestBody.create(MEDIA_TYPE_JSON, gson.toJson(payload)))
				.build();
		Response response = client.newCall(request).execute();

		if (response.isSuccessful()) {
			RespModel<String> resp = gson.fromJson(response.body().string(),RespModel.class);
			if (StringUtils.equals(resp.getStatus(), "success")) {
				return "success";
			} else {
				switch (new Integer(resp.getErrorcode())) {
				case 201:
					return "parameter missing";
				case 202:
					return resp.getReason();
				default:
					return resp.getReason();
				}

			}
		} else {
			return "Service error";
		}
	}

	protected String getFallback() {
		return "Service error";
	}

	public static void main(String[] args) {
		String smsresult = new SmsSendUtil(
				"http://127.0.0.1:8083/ehualu-msg/msg/msg/send",
				"735cc04b-f42e-4074-b061-606d01d15b96", "18660811312", "吃了没！",
				"reg").execute();
		System.out.println(smsresult);
	}
}
